package com.weishaoying.example.base.aware;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author WeiShaoying
 * @date 2018/4/4
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    private SpringContextUtil() {
        //单例
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    //通过类型获得Bean
    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    //通过name获得bean,类型为了不用强制转换
    public static <T> T getBean(String name, Class<T> clazz) {
        return context.getBean(name, clazz);
    }

}
